<template>
  <div class="mapbox-map">
    <div class="map-container" :id="mapId"></div>
  </div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, watch } from 'vue'
import mapboxgl from 'mapbox-gl'
import { setHelper, deleteHelper } from '@/utils/map'
// import MapboxLanguage from "@mapbox/mapbox-gl-language";

let _map

const props = defineProps({
  mapId: {
    type: String,
    required: true,
  },
  center: {
    type: Object,
    default: () => [106.49328310804757, 29.768499553618765],
  },
  zoom: {
    type: Number,
    default: 12,
  },
})

const emits = defineEmits(['after-map-loaded', 'before-map-destroyed'])

onMounted(() => {
  const mapboxKey =
    'pk.eyJ1IjoiYWxsZW5jaGlhbmdjbiIsImEiOiJjanQ2bWVoaTkwaXF0NDRyMW54dHpucjZ2In0.fiVf9bycG4NOa0tgjwu68Q'
  const tdtKey = 'a49a9220798216424e34b531cb3fa5b2'
  mapboxgl.accessToken = mapboxKey

  _map = new mapboxgl.Map({
    container: props.mapId,
    // style: "mapbox://styles/mapbox/streets-v12",
    style: {
      version: 8,
      sources: {
        // 天地图注记服务
        'tdt-labels': {
          type: 'raster',
          tiles: [
            `https://t0.tianditu.gov.cn/cia_w/wmts?tk=${tdtKey}&service=WMTS&version=1.0.0&request=GetTile&layer=cia&style=default&format=tiles&transparent=true&TileMatrixSet=w&TileMatrix={z}&TileRow={y}&TileCol={x}`,
          ],
          tileSize: 256,
        },
      },
      layers: [
        {
          id: 'tdt-labels',
          type: 'raster',
          source: 'tdt-labels',
        },
      ],
      glyphs: './font/{fontstack}/{range}.pbf',
    },
    center: props.center,
    zoom: props.zoom,
    antialias: true,
    maxPitch: 80,
  })

  setHelper(props.mapId, _map)

  _map.on('load', () => {
    // initLanguage();
    emits('after-map-loaded', props.mapId, _map)
  })
})

onBeforeUnmount(() => {
  if (_map) {
    emits('before-map-destroyed', props.mapId, _map)
    deleteHelper(props.mapId)
  }
})
</script>

<style lang="scss" scoped>
.mapbox-map {
  position: relative;
  width: 100%;
  height: 100%;

  .map-container {
    width: 100%;
    height: 100%;
    border-radius: inherit;
    overflow: hidden;
  }
}
</style>
